/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.stress.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.springblade.common.cache.DictBizCache;
import org.springblade.common.cache.StressCache;
import org.springblade.common.constant.StressConstant;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.icivil.entity.FirstData;
import org.springblade.modules.icivil.entity.IndexData;
import org.springblade.modules.icivil.entity.PositionData;
import org.springblade.modules.stress.entity.Channel;
import org.springblade.modules.stress.entity.Position;
import org.springblade.modules.stress.entity.Sensor;
import org.springblade.modules.stress.mapper.SensorMapper;
import org.springblade.modules.stress.service.IAlarmService;
import org.springblade.modules.stress.service.IChannelService;
import org.springblade.modules.stress.service.IPositionService;
import org.springblade.modules.stress.service.ISensorService;
import org.springblade.modules.stress.vo.SensorVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 传感器设备管理表 服务实现类
 *
 * @author Yanzujian
 * @since 2021-01-09
 */
@Service
@AllArgsConstructor
public class SensorServiceImpl extends BaseServiceImpl<SensorMapper, Sensor> implements ISensorService {
	private final IChannelService channelService;
	private final IPositionService positionService;
	private final BladeRedis bladeRedis;


	@Override
	public IPage<SensorVO> selectSensorPage(IPage<SensorVO> page, SensorVO sensor) {
		return page.setRecords(baseMapper.selectSensorPage(page, sensor));
	}

	@Override
	@Transactional
	public boolean removeSensorByIds(String ids) {
		//1、删除关联树
		channelService.remove(Wrappers.<Channel>query().lambda().gt(Channel::getSensorType, StressConstant.STRESS_SENSOR_TYPE_POSITION) //大于测点: 温度，振弦
			.in(Channel::getChannelId, Func.toLongList(ids)));
		//2、删除本体
		return removeByIds(Func.toLongList(ids));
	}

	@Override
	@Transactional
	public boolean updateSensor(Sensor sensor) {
		boolean re = saveOrUpdate(sensor);
		if (re) {
			//测点
			Channel channel = channelService.getOne(Wrappers.<Channel>query().lambda().eq(Channel::getChannelId, sensor.getId()));
			channel.setParentId(sensor.getPositionId());
			channel.setCode(sensor.getCode());
			channel.setName(sensor.getName());
			channelService.saveOrUpdate(channel);

			//保存数据键值对(sensorCode:channelCode : deviceId:sensorId)
			Position position = positionService.getById(sensor.getPositionId());
			//1、获取设备id
			String deviceId = position.getDeviceId().toString();
//				//2、键值对:value
//				String value = deviceId + ":" + sensor.getId();
			//3、键值对:key
			String sensorCode = getById(sensor.getParentId()).getCode();
//				String key = sensorCode + ":" + sensor.getCode();
//
//				//键值对(sensorCode:channelCode : deviceId:sensorId)
//				String codeKey = "code:"+key;
//				bladeRedis.set(codeKey,value);
//				//键值对(deviceId:sensorId : sensorCode:channelCode)
//				String idKey = "id:"+value;
//				bladeRedis.set(idKey,key);


			//传感器list索引
//			String indexKey = "index:" + deviceId;
//			IndexData indexData = new IndexData();
//			indexData.setSensorId(sensor.getId().toString());
//			indexData.setSensorSorted(sensor.getSensorSort());
//			indexData.setDeviceCode(deviceId);
//			indexData.setChannelCode(sensor.getCode());
//			indexData.setSensorCode(sensorCode);
//			indexData.setSensorName(sensor.getName());
//			indexData.setStatusTypeName(DictBizCache.getValue("stress_sensor_status_type", sensor.getStatusType()));
//
//			Boolean isExsited = bladeRedis.exists(indexKey);
//
//			if (isExsited){
//				List<IndexData> indexDataList = bladeRedis.get(indexKey);
//				boolean flag = false;//是否有重复数据
//				for (IndexData data: indexDataList) {
//					if (data.getSensorId().equals(sensor.getId().toString())) {
//						flag = true;
//						break;
//					}
//				}
//				if (!flag){
//					indexDataList.add(indexData);
//					//排序
//					List<IndexData> dataSorts = indexDataList.stream()
//						.sorted(Comparator.comparing(IndexData::getSensorSorted))
//						.collect(Collectors.toList());
//					bladeRedis.set(indexKey,dataSorts);
//				}
//			}else {
//				List<IndexData> indexDataList = new ArrayList<>();
//				indexDataList.add(indexData);
//				//排序
//				List<IndexData> dataSorts = indexDataList.stream()
//					.sorted(Comparator.comparing(IndexData::getSensorSorted))
//					.collect(Collectors.toList());
//				bladeRedis.set(indexKey,dataSorts);
//			}

			//测点索引
			PositionData positionData = new PositionData();
			positionData.setPositionId(position.getId().toString());
			positionData.setName(position.getLocal());
			positionData.setStatusTypeName(DictBizCache.getValue("stress_position_status", position.getPositionStatus()));

			String positionIndexKey = "position:" + deviceId;
			Boolean isKeyExsited = bladeRedis.exists(positionIndexKey);
			if (isKeyExsited){
				List<PositionData> pDataList = bladeRedis.get(positionIndexKey);
				boolean flag = false;//是否有重复数据
				for (PositionData data: pDataList) {
					if (data.getPositionId().equals(position.getId().toString())) {
						flag = true;
						break;
					}
				}
				if (!flag){
					pDataList.add(positionData);
					//排序
					List<PositionData> pdSorts = pDataList.stream()
						.sorted(Comparator.comparing(PositionData::getPositionId))
						.collect(Collectors.toList());
					bladeRedis.set(positionIndexKey,pdSorts);
				}
			}else {
				List<PositionData> positionDataList = new ArrayList<>();
				positionDataList.add(positionData);
				//排序
				List<PositionData> pdSorts = positionDataList.stream()
					.sorted(Comparator.comparing(PositionData::getPositionId))
					.collect(Collectors.toList());
				bladeRedis.set(positionIndexKey,pdSorts);
			}

			//传感器索引
			FirstData fd = new FirstData();
			fd.setSensorId(sensor.getId().toString());
			fd.setFirstValue(sensor.getFirstValue().toString());
			fd.setSensorCode(sensorCode);
			fd.setChannelCode(sensor.getCode());
			String fdKey = "sensor:"+ position.getId() + ":" + sensor.getSensorType();
			bladeRedis.set(fdKey,fd);

			return true;
		}
		return false;
	}

	@Override
	@Transactional
	public boolean saveSensor(Sensor sensor) {
		boolean re = save(sensor);
		if (re){
			if (sensor.getId() > 0){
				//传感器
				Channel channel = new Channel();
				channel.setChannelId(sensor.getId());
				channel.setParentId(sensor.getPositionId());
				channel.setCode(sensor.getCode());
				channel.setName(sensor.getName());
				channel.setSensorType(sensor.getSensorType());
				channel.setIsDeleted(BladeConstant.DB_NOT_DELETED);
				channelService.save(channel);

				//保存数据键值对(sensorCode:channelCode : deviceId:sensorId)
				Position position = positionService.getById(sensor.getPositionId());
				//1、获取设备id
				String deviceId = position.getDeviceId().toString();
//				//2、键值对:value
//				String value = deviceId + ":" + sensor.getId();
				//3、键值对:key
				String sensorCode = getById(sensor.getParentId()).getCode();
//				String key = sensorCode + ":" + sensor.getCode();
//
//				//键值对(sensorCode:channelCode : deviceId:sensorId)
//				String codeKey = "code:"+key;
//				bladeRedis.set(codeKey,value);
//				//键值对(deviceId:sensorId : sensorCode:channelCode)
//				String idKey = "id:"+value;
//				bladeRedis.set(idKey,key);

				//传感器list索引
//				String indexKey = "index:" + deviceId;
//				IndexData indexData = new IndexData();
//				indexData.setSensorId(sensor.getId().toString());
//				indexData.setSensorSorted(sensor.getSensorSort());
//				indexData.setDeviceCode(deviceId);
//				indexData.setChannelCode(sensor.getCode());
//				indexData.setSensorCode(sensorCode);
//				indexData.setSensorName(sensor.getName());
//				indexData.setStatusTypeName(DictBizCache.getValue("stress_sensor_status_type", sensor.getStatusType()));
//
//				Boolean isExsited = bladeRedis.exists(indexKey);
//
//				if (isExsited){
//					List<IndexData> indexDataList = bladeRedis.get(indexKey);
//					boolean flag = false;//是否有重复数据
//					for (IndexData data: indexDataList) {
//						if (data.getSensorId().equals(sensor.getId().toString())) {
//							flag = true;
//							break;
//						}
//					}
//					if (!flag){
//						indexDataList.add(indexData);
//						//排序
//						List<IndexData> dataSorts = indexDataList.stream()
//							.sorted(Comparator.comparing(IndexData::getSensorSorted))
//							.collect(Collectors.toList());
//						bladeRedis.set(indexKey,dataSorts);
//					}
//				}else {
//					List<IndexData> indexDataList = new ArrayList<>();
//					indexDataList.add(indexData);
//					//排序
//					List<IndexData> dataSorts = indexDataList.stream()
//						.sorted(Comparator.comparing(IndexData::getSensorSorted))
//						.collect(Collectors.toList());
//					bladeRedis.set(indexKey,dataSorts);
//				}

				//测点索引
				PositionData positionData = new PositionData();
				positionData.setPositionId(position.getId().toString());
				positionData.setName(position.getLocal());
				positionData.setStatusTypeName(DictBizCache.getValue("stress_position_status", position.getPositionStatus()));

				String positionIndexKey = "position:" + deviceId;
				Boolean isKeyExsited = bladeRedis.exists(positionIndexKey);
				if (isKeyExsited){
					List<PositionData> pDataList = bladeRedis.get(positionIndexKey);
					boolean flag = false;//是否有重复数据
					for (PositionData data: pDataList) {
						if (data.getPositionId().equals(position.getId().toString())) {
							flag = true;
							break;
						}
					}
					if (!flag){
						pDataList.add(positionData);
						//排序
						List<PositionData> pdSorts = pDataList.stream()
							.sorted(Comparator.comparing(PositionData::getPositionId))
							.collect(Collectors.toList());
						bladeRedis.set(positionIndexKey,pdSorts);
					}
				}else {
					List<PositionData> positionDataList = new ArrayList<>();
					positionDataList.add(positionData);
					//排序
					List<PositionData> pdSorts = positionDataList.stream()
						.sorted(Comparator.comparing(PositionData::getPositionId))
						.collect(Collectors.toList());
					bladeRedis.set(positionIndexKey,pdSorts);
				}

				//传感器索引
				FirstData fd = new FirstData();
				fd.setSensorId(sensor.getId().toString());
				fd.setFirstValue(sensor.getFirstValue().toString());
				fd.setSensorCode(sensorCode);
				fd.setChannelCode(sensor.getCode());
				String fdKey = "sensor:"+ position.getId() + ":" + sensor.getSensorType();
				bladeRedis.set(fdKey,fd);

				return true;
			}
		}
		return false;
	}

}
